/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.dragonsoftbravo.tvwebui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import junit.framework.Test;

import java.security.Key;

/*
 * MainActivity class that loads MainFragment
 */
public class MainActivity extends Activity implements View.OnClickListener {
    /**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWebView();
    }

    String homeUrl = "http://10.0.2.2";
    String curUrl = homeUrl;
    EditText etUrl;
    WebView webView;

    private void initWebView() {
        clearWebViewCache();
        this.webView = (WebView) this.findViewById(R.id.webview);
        etUrl = (EditText) findViewById(R.id.url);
        this.webView.getSettings().setJavaScriptEnabled(true);
        this.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
        this.webView.setWebViewClient(new webViewClient());
        this.webView.setWebChromeClient(new AlertWebViewClient());
        this.webView.loadUrl(curUrl);
    }

    public void clearWebViewCache() {
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class webViewClient extends WebViewClient {

        //重写shouldOverrideUrlLoading方法，使点击链接后不使用其他的浏览器打开。

        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            curUrl = url;
            view.loadUrl(url);

            //如果不需要其他对点击链接事件的处理返回true，否则返回false

            return true;

        }
    }

    /**
     * 解决webview中无法弹出alert的问题
     */
    class AlertWebViewClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示：").setMessage(message)
                    .setPositiveButton("确定",
                            new AlertDialog.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    result.confirm();
                                }
                            });
            b2.setCancelable(false);
            b2.create();
            b2.show();
            return true;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(!findViewById(R.id.url).hasFocus()){
                findViewById(R.id.url).requestFocus();
                return true;
            }
        }else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
            this.webView.requestFocus();
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    public void onClick(View v) {
        webView.loadData("", "text/html", "UTF-8");
        switch (v.getId()) {
            case R.id.go:
                String url = etUrl.getText().toString();
                if (url.length() == 0) return;
                if (url.startsWith("http")) {
                    curUrl = url;
                } else {
                    curUrl = "http://" + url;
                }
                break;
            case R.id.home:
                curUrl = homeUrl;
                break;
            case R.id.refresh:

                break;
        }
        webView.loadUrl(curUrl);
    }
}
